/**
 * 
 */
package org.framework.pub.util;

import java.util.List;

import org.apache.log4j.Logger;
import org.framework.app.exception.AppException;
import org.framework.app.exception.SysException;
import org.framework.app.model.dao.Sql;
import org.framework.app.web.entity.PagInfo;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

/**
 * @Title PageUtil.java
 * @version 1.0
 * @author DapengZhang
 * @Created 2013-1-15 Copyright (c) 2013 PanGene InfoAnalytics.
 * 
 * @Description: 分页工具类
 */
public class PageUtil {
	private static final Logger logger = Logger.getLogger(PageUtil.class);

	public static PagInfo initPagInfoJDBC(JdbcTemplate jdbcTemplate, String sql,
			List<Object> params, PagInfo pagInfo) throws SysException,
			AppException {
		int count; // 总记录数
		int rowLimit;
		int pageSize = pagInfo.getRp(); // 每页显示记录数
		int pageNo = pagInfo.getPage(); // 第几页
		if (pageNo < 0) {
			pageNo = 1;
		}

		PagInfo pageInfo = new PagInfo();

		count = getCountJDBC(jdbcTemplate, sql, params);
		// 校验查询的记录是否大于系统规定的最大数目（略，后续实现）
		rowLimit = pagInfo.getRowLimit();
		/**
		 * pageInfo.setCount(count); if (count % pageSize == 0) { // 计算页数
		 * pageInfo.setTotal(count / pageSize); } else { pageInfo.setTotal(count
		 * / pageSize + 1); } if (pageNo < 0) { // 没有初始化默认为第一页 pageNo = 1; }
		 */

		pageInfo.setTotal(count);
		pageInfo.setPage(pageNo);
		pageInfo.setRp(pageSize);

		return pageInfo;
	}

	/**
	 * 进行分页查询数据
	 */
	public static List<Object> query(JdbcTemplate jdbcTemplate, StringBuffer sql,List<Object> params,RowMapper rowMapper,
			PagInfo pagInfo) throws AppException, SysException {
		StringBuffer pagSql = getPagSql(sql,params, pagInfo);
		try {
			@SuppressWarnings("unchecked")
			List<Object> obj = jdbcTemplate.query(pagSql.toString(), params.toArray(), rowMapper);
			return obj;
		} catch (Exception ex) {
			throw new SysException("100010", "分页查询出现异常！", ex);
		}
	}
	
	/**
	 * 通过Spring的JdbcTemplate设置获取分页SQL语句<br>
	 * 获得分页查询的SQL 获得的SQL仅仅使用于MySql的JDBC方式的分页查询
	 */
	public static StringBuffer getPagSql(StringBuffer pageSql,List<Object> params, PagInfo pagInfo) {
		int pageSize = pagInfo.getRp(); // 每页显示记录数
		int pageNo = pagInfo.getPage(); // 第几页
		if (pageNo < 0)
			pageNo = 1;

		pageSql.insert(0,
				" select * from ( select * from ( ");
		pageSql
				.append(" )rows_) datas_  limit ?,? ");
		
		params.add((pageNo-1) * pageSize);
		params.add(pageSize);

		return pageSql;
	}
	
	/**
	 * 通过Spring的JdbcTemplate查询总记录数
	 * @param sql 目标查询语句
	 * @param params
	 */
	public static int getCountJDBC(JdbcTemplate jdbcTemplate, String sql,
			List<Object> params) throws AppException, SysException {
		int count = 0;
		String coutSql = getCountSql(sql);
		try {
			count = jdbcTemplate
					.queryForInt(coutSql, params.toArray());
		} catch (Exception ex) {
			throw new SysException("", "", ex);
		}
		return count;
	}
	
	/**
	 * 获得查询数目总数的SQL, 用于JDBC的查询
	 * @param sql
	 * @return String
	 */
	public static String getCountSql(String sql) {
		StringBuffer pagingSelect = new StringBuffer();
		pagingSelect.append("select count(*) from (");
		pagingSelect.append(sql);
		pagingSelect.append(") rows_");
		return pagingSelect.toString();
	}

}
